package bank

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// Bank /**银行流水

func Bank(r *gin.Engine) {

	bank := r.Group("/bank")
	{

		account := bank.Group("/account")
		{
			account.GET(sql.RequestList, bankAccountList)
		}

		flow := bank.Group("/flow")
		{
			flow.POST(sql.RequestAdd, flowAdd)
			flow.POST(sql.RequestUpdate, flowUpdates)
			flow.GET(sql.RequestList, flowList)
			flow.GET(sql.RequestData, flowData)
			flow.GET(sql.RequestDelete, flowDelete)
		}

		statement := bank.Group("/statement")
		{
			statement.POST(sql.RequestAdd, statementAdd)
			statement.POST(sql.RequestUpdate, statementUpdates)
			statement.GET(sql.RequestList, statementList)
			statement.GET(sql.RequestData, statementData)
			statement.GET(sql.RequestDelete, statementDelete)
		}
		incomeExpense := bank.Group("/incomeExpense")
		{
			incomeExpense.POST(sql.RequestAdd, incomeExpenseAdd)
			incomeExpense.POST(sql.RequestUpdate, incomeExpenseUpdates)
			incomeExpense.GET(sql.RequestList, incomeExpenseList)
			incomeExpense.GET(sql.RequestData, incomeExpenseData)
			incomeExpense.GET(sql.RequestDelete, incomeExpenseDelete)
		}

		adjustment := bank.Group("/adjustment")
		{
			adjustment.POST(sql.RequestAdd, adjustmentAdd)
			adjustment.GET(sql.RequestList, adjustmentList)
			adjustment.DELETE(sql.RequestDelete, adjustmentDelete)
		}

	}
}

func bankAccountList(c *gin.Context) {
	sql.HttpList(c, &[]model.BankAccount{}, func(db *gorm.DB) *gorm.DB {
		db = db.Order("sort")
		return db
	})
}

/**
 *银行调帐
 */
func bankAdjustment(c *gin.Context) {
	sql.HttpHandle(sql.ADD, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var bean model.BankAdjustment
		if err := c.Bind(&bean); err != nil {
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}
		var tx = db.Begin()
		// 1、创建调账
		if err := tx.Create(&bean).Error; err != nil {
			db.Error = errors.New(sql.ErrorService)
			tx.Callback()
			return tx, nil
		}
		// 2、修改付款账户余额
		if err := balanceChanges(tx, bean.PaymentAccountId, bean.Money, false); err != nil {
			return tx, nil
		}

		// 3、修改收款账户余额
		if err := balanceChanges(tx, bean.CollectionAccountId, bean.Money, true); err != nil {
			return tx, nil
		}

		tx.Commit()
		return db, nil
	})
}

/*
*
*银行账户余额变动
 */
func balanceChanges(tx *gorm.DB, accountId int, money float64, isAdd bool) error {
	var operator string
	if isAdd {
		operator = "balance + ?"
	} else {
		operator = "balance - ?"
	}
	err := tx.Model(&model.BankAccount{}).
		Where("id = ?", accountId).
		Updates(map[string]interface{}{"balance": gorm.Expr(operator, money)}).Error
	if err != nil {
		tx.Error = errors.New(sql.ErrorService)
		tx.Callback()
		return err
	}
	return nil
}
